package userloginandregistertest



import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class UserController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    //登录验证拦截器
    def beforeInterceptor = [action: this.&checkUserLogin,only:['list']]//only表示该拦截器仅仅拦截指定操作，也可用except来代替only，表示除此之外的操作

    def index(){
        render(view: 'login')
    }

    def login(){
        def u = User.findByLoginAndPassword(params.login,params.password)
        if(u){
            session.welcomeString="${u.name}，欢迎登录"
            session.loginUser=u
            redirect action: 'list'
        }else{
            flash.message='用户名或密码错误，请查证!'
            redirect action: 'index'
        }
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model: [userInstanceCount: User.count()]
    }

    def toReg(){
        render(view: 'register')
    }
    def register(){
        respond new User(params)
    }

    @Transactional
    def save(User userInstance) {
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view: 'register'
            return
        }

        def u = User.findAllByLogin(userInstance.login)
        if(u){
            flash.message = '该用户名已经存在!'
            redirect action: 'toReg'
            return
        }

        userInstance.save flush: true

        flash.message = '注册成功，请登录!'
        redirect action: 'toReg'
    }

    private checkUserLogin(){
        if(!session.loginUser){
            flash.message='您尚未登录，请登录后操作!'
            redirect(action: 'index')
            false
        }
    }

    protected void notFound() {
        request.withFormat {
            form {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'userInstance.label', default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }
}
